package com.cloud.demo2020;

import com.alibaba.fastjson.JSONObject;
import com.cloud.demo2020.common.ResultBean;
import com.cloud.demo2020.config.GuavaConfig;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.RateLimiter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

@Component
public class IpFilter implements GlobalFilter {

    @Autowired
    LoadingCache<String, RateLimiter> guavaCache;

    private Logger log = LoggerFactory.getLogger(getClass());
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //r.acquire()
        //Ratel
        log.info("config:" + GuavaConfig.configMap);
        String clientIp = exchange.getRequest().getRemoteAddress().getHostString();
        RateLimiter rateLimiter = null;
        ResultBean error = new ResultBean(false, "同学,你访问的太频繁了");
        error.setCode(303);
        ServerHttpResponse resp = exchange.getResponse();
        try {
            rateLimiter = guavaCache.get(clientIp);
            boolean flag = rateLimiter.tryAcquire();
            if (flag) {
                return chain.filter(exchange);
            } else {

                return getVoidMono(exchange, error);
            }
        } catch (Exception e) {
            log.warn(e.getMessage());
            return getVoidMono(exchange, error);
        }

    }

    private Mono<Void> getVoidMono(ServerWebExchange serverWebExchange, ResultBean body) {
        ServerHttpResponse resp = serverWebExchange.getResponse();
        resp.setStatusCode(HttpStatus.OK);
        byte[] bytes = JSONObject.toJSONString(body).getBytes(Charset.defaultCharset());
        DataBuffer buffer = resp.bufferFactory().wrap(bytes);
        resp.getHeaders().add(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");
        return resp.writeWith(Mono.just(buffer));
    }
}
